package com.concurrency.aqs;

import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>测试ReentrantLock</p>
 */
public class ReentrantLockTest {

    private static int sum = 0;
    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        for (int i = 1; i < 4; i++) {
            Thread thread = new Thread(() -> {

                try {
                    //加锁
                    lock.lock();
                    for (int j = 0; j < 10000; j++) {
                        sum++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("111111");
                    // 释放锁
                    lock.unlock();
                    System.out.println(Thread.currentThread().getName() + " unlock");
                }
            }, "thread_" + i);
            thread.start();
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(sum);


    }

}
